package webapi

import (
	"strings"

	"iot-base/common/dbconn"

	"github.com/gin-gonic/gin"
)

func getByCondition(pObj dbconn.DBObjIDer, condition map[string]interface{}) ([]map[string]interface{}, error) {
	result := make([]map[string]interface{}, 0, 1)
	err := dbconn.DBConnection.Model(pObj).Where(condition).Order("uid").Find(&result).Error
	return result, err
}

func queryByCondition(idparam string, pObj dbconn.DBObjIDer, c *gin.Context) bool {
	query := strings.ToLower(idparam)
	if query == "condition" {
		conditions := c.Request.URL.Query()
		if conditions == nil {
			SendError("no condition", ParamMissed, c)
		} else {
			cmap := make(map[string]interface{})
			for k, v := range conditions {
				if len(v) >= 0 && !strings.Contains(k, " ") {
					cmap[k] = v[0]
				}
			}
			res, err := getByCondition(pObj, cmap)
			if err != nil {
				SendError(err.Error(), DBError, c)
			} else {
				SendResult(res, nil, c)
			}
		}

		return true
	}

	return false
}
